<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Category;
use Illuminate\Http\JsonResponse;

class CategoryController extends Controller
{
    /**
     * 获取分类下的文章列表
     *
     * @param Category $category
     * @return JsonResponse
     */
    public function posts(Category $category): JsonResponse
    {
        try {
            $posts = $category->posts()
                ->with(['user', 'category', 'tags'])
                ->where('status', 'published')
                ->whereNotNull('published_at')
                ->where('published_at', '<=', now())
                ->orderBy('published_at', 'desc')
                ->get()
                ->map(function ($post) {
                    return [
                        'id' => $post->id,
                        'title' => $post->title,
                        'slug' => $post->slug,
                        'excerpt' => $post->excerpt,
                        'published_at' => $post->published_at,
                        'views' => $post->views ?? 0,
                        'user' => $post->user ? [
                            'id' => $post->user->id,
                            'name' => $post->user->name,
                        ] : null,
                        'category' => $post->category ? [
                            'id' => $post->category->id,
                            'name' => $post->category->name,
                            'slug' => $post->category->slug,
                        ] : null,
                        'tags' => $post->tags->map(function ($tag) {
                            return [
                                'id' => $tag->id,
                                'name' => $tag->name,
                                'slug' => $tag->slug,
                            ];
                        }),
                    ];
                });

            return response()->json([
                'success' => true,
                'posts' => $posts,
                'category' => [
                    'id' => $category->id,
                    'name' => $category->name,
                    'slug' => $category->slug,
                ],
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '获取文章列表失败',
                'error' => $e->getMessage(),
            ], 500);
        }
    }
}